<template>
  <div class="app-container">
    <el-row style="margin-bottom:20px" type="flex" justify="end" align="midden">
      <el-button size="small" type="primary" icon="el-icon-plus" @click="(visitDataDialog=true,isEdit = false)">新 增</el-button>
    </el-row>
    <el-table
      ref="multipleTable"
      :data="tableData"
      border
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column type="index" label="排序" align="center" width="55" />
      <!-- <el-table-column prop="name" label="类型名称" align="center" /> -->
      <!-- <el-table-column prop="customerName" label="客户名称" align="center" /> -->
      <el-table-column prop="linkman" label="被拜访人" align="center" />
      <el-table-column prop="linkPhone" label="联系电话" align="center" />
      <el-table-column prop="wxNo" label="微信号" align="center" />
      <el-table-column prop="position" label="职位" align="center" />
      <el-table-column align="center" label="拜访时间">
        <template slot-scope="{row}">
          <span>{{ row.visitTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="remark" label="描述" align="center" /> -->
      <el-table-column label="操作" fixed="right" align="center" width="250px">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleModify(row)">编辑记录</el-button>
          <!-- <el-button v-if="row.status===0" size="mini" type="success" @click="handleEnable(row)">启用</el-button>
          <el-button v-if="row.status===1" size="mini" type="warning" @click="handleDisable(row)">禁用</el-button> -->
          <el-button size="mini" type="danger" @click="handleDelete(row)"> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <!-- 查看/编辑客户拜访信息 -->
    <el-dialog
      title="查看/编辑客户拜访信息"
      :visible.sync="visitDataDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="800px"
      @close="closeVisit"
    >
      <el-form ref="visitDataForm" :model="visitDataForm" :rules="visitDataRules" label-width="140px" class="demo-visitDataForm">
        <el-form-item label="被拜访人名称" prop="linkman">
          <el-input v-model="visitDataForm.linkman" placeholder="请输入被拜访人名称" />
        </el-form-item>
        <el-form-item label="被拜访人联系电话" prop="linkPhone">
          <el-input v-model="visitDataForm.linkPhone" placeholder="请输入被拜访人联系电话" />
        </el-form-item>
        <el-form-item label="被拜访人微信号" prop="wxNo">
          <el-input v-model="visitDataForm.wxNo" placeholder="请输入被拜访人微信号" />
        </el-form-item>
        <el-form-item label="被拜访人职位" prop="position">
          <el-input v-model="visitDataForm.position" placeholder="请输入被拜访人职位" />
        </el-form-item>
        <el-form-item label="拜访人" prop="visitName">
          <el-input v-model="visitDataForm.visitName" placeholder="请输入拜访人" />
        </el-form-item>
        <el-form-item label="拜访时间" prop="visitTime">
          <el-date-picker
            v-model="visitDataForm.visitTime"
            type="datetime"
            value-format="timestamp"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="拜访记录" prop="remark">
          <!-- <tinymce v-if="visitDataDialog" v-model="visitDataForm.remark" :height="400" /> -->
          <el-input
            v-model="visitDataForm.remark"
            type="textarea"
            placeholder="请输入客户资料"
            :autosize="{ minRows: 4, maxRows: 6}"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="客户资料上传" prop="attachmentList">
          <el-upload
            class="upload-demo"
            action="#"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="visitDataForm.attachmentList"
            :http-request="handleAvatarRequest"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="confimVisit">确 定</el-button>
        <el-button @click="visitDataDialog = false">取 消</el-button>
        <!-- <el-button @click="visitDataDialog = false">草 稿</el-button> -->
      </span>
    </el-dialog>

  </div>
</template>

<script>
// import tinymce from '@/components/Tinymce'
import Pagination from '@/components/Pagination'
import { getInfoFromOss } from '@/api/public'
import { randomString } from '@/utils'
import axios from 'axios'
import {
  visitPageList,
  visitAdd,
  visitGetById,
  visitUpdateById,
  visitDeleteById
} from '@/api/customer'
export default {
  name: 'CustomerVisit',
  components: {
    Pagination
    // tinymce
  },
  data() {
    return {
      id: this.$route.query.id,
      currentRow: {}, // 当前行
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 10
      },
      tableData: [],
      isEdit: false,
      visitDataDialog: false,
      visitDataForm: {
        'name': '',
        'businessId': '0',
        'status': '1',
        'customerId': '',
        'customerName': '',
        'linkman': '',
        'linkPhone': '',
        'wxNo': '',
        'position': '',
        'remark': '',
        'visitName': '',
        'visitTime': '',
        'attachmentList': []
      },
      visitDataRules: {
        linkman: [
          { required: true, message: '请输入被拜访人名称', trigger: 'blur' }
        ],
        linkPhone: [
          { required: true, message: '请输入被拜访人联系电话', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleModify(row) {
      this.isEdit = true
      this.currentRow = row
      visitGetById({
        id: row.id
      }).then(res => {
        this.visitDataForm = res.data
        this.visitDataForm.attachmentList = res.data.attachmentList || []
        this.visitDataDialog = true
      })
    },
    handleDelete(row) {
      this.$confirm('是否删除此条记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        visitDeleteById({ id: row.id }).then(res => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleAvatarRequest(res) {
      const file = res.file
      // const raw = {
      //   raw: file,
      //   name: file.name
      // }
      getInfoFromOss().then(response => {
        // console.log(response)
        const info = response.data
        const randomStr = randomString(13)
        const param = new FormData()
        param.append('key', randomStr)
        param.append('policy', info.policy)
        param.append('OSSAccessKeyId', info.accessKeyId)
        param.append('success_action_status', 200)
        param.append('signature', info.signature)
        param.append('file', file)
        param.append('chunk', '0')
        const config = {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Access-Control-Allow-Origin': '*'
          }
        }
        axios.post(info.host, param, config).then(response => {
          // console.log('图片提交成功')
          // console.log(response)
          if (response.status === 200) {
            this.$message({ message: '文件上传成功', type: 'success' })
            const imgUrl = info.host + '/' + randomStr
            const index = file.name.lastIndexOf('.')
            const n = file.name.slice(index)
            let val = ''
            if (n === '.jpg' || n === '.jpeg' || n === '.png' || n === '.JPG' || n === '.JPEG') {
              val = 1
            }
            if (n === '.mp4' || n === '.mpeg' || n === '.rmvb' || n === '.avi' || n === '.3gp') {
              val = 2
            }

            this.visitDataForm.attachmentList.push({
              'name': file.name,
              'type': val,
              'suffix': n,
              'size': file.size,
              'url': `${imgUrl}`,
              'uid': file.uid
            })
          } else {
            this.$message({ message: '文件上传失败', type: 'error' })
          }
          // console.log(imgUrl, 'imgUrl')
        })
      })
      // this.uploadImgToOss(raw).then(response => {
      //   const url = response
      //   const index = file.name.lastIndexOf('.')
      //   const n = file.name.slice(index)
      //   this.visitDataForm.attachmentList.push({
      //     'name': file.name,
      //     'type': '',
      //     'suffix': n,
      //     'size': file.size,
      //     'url': url,
      //     'uid': file.uid
      //   })
      // })
    },
    handleRemove(file, fileList) {
      this.visitDataForm.attachmentList = fileList
    },
    handlePreview(file) {
      // console.log(file)
      // if (this.isEdit) {
      //   let params = {}
      //   params = JSON.parse(file)
      //   const type = params.url.split('.')[4]
      //   if (
      //     type === 'doc' ||
      //   type === 'docx' ||
      //   type === 'xlsx' ||
      //   type === 'xls' ||
      //   type === 'ppt' ||
      //   type === 'pptx'
      //   ) {
      //     // 在當前瀏覽器頁面直接下載
      //     document.location.href = params.url
      //   } else {
      //     // 圖片會直接在瀏覽器中打開所以，打開新的頁面
      window.open(file.url, 'hello')
      //   }
      // window.open(encodeURI('https://ossdev0.jiabala.com/JPtybwjLUYMSn.xlsx'), 'hello')
      // }
    },
    confimVisit() {
      this.$refs.visitDataForm.validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.visitDataForm)
          if (data.attachmentList.length > 0) {
            data.attachmentList.forEach(i => {
              i.status && delete i.status
              i.uid && delete i.uid
              i.id && delete i.id
            })
          }
          data.customerId = this.id
          if (this.isEdit) {
            data.id = this.currentRow.id
            visitUpdateById(data).then(res => {
              this.$message.success('修改成功')
              this.visitDataDialog = false
              this.getList()
            })
          } else {
            visitAdd(data).then(res => {
              this.$message.success('新增成功')
              this.visitDataDialog = false
              this.getList()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    closeVisit() {
      this.visitDataForm = {
        'name': '',
        'businessId': '0',
        'status': '1',
        'customerId': '',
        'customerName': '',
        'linkman': '',
        'linkPhone': '',
        'wxNo': '',
        'position': '',
        'remark': '',
        'visitName': '',
        'visitTime': '',
        'attachmentList': []
      }
    },
    getList() {
      visitPageList({
        'name': '',
        'currentPage': this.listQuery.currentPage,
        'pageSize': this.listQuery.pageSize,
        'businessId': '0',
        'customerId': this.id
      }).then(res => {
        const { records, total } = res.data
        this.tableData = records
        this.total = total
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.icon-img{
  width: 100px;
  height: 100px;
}
 /deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  /deep/.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  /deep/.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 130px;
    height: 130px;
    line-height: 130px;
    text-align: center;
  }
  /deep/.avatar {
    width: 130px;
    height: 130px;
    display: block;
  }
</style>
